package com.liu.sx.decode;

import com.liu.sx.pojo.BW;
import com.liu.sx.util.BwUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;

/**
 * TAG =   1字节
 * 地址为：6字节
 * 数据长度1 字节
 * 功能吗  1节
 *
 */

@Slf4j
public class MyReplayingDecoderUp extends ReplayingDecoder<Void> {

    private static  final int TAG =  0xFB;// 251 (127)(-128)
    private static  final  byte END_TAG =0x16;//22
    private static  final int BASE_LEN =1+6 +1 +1;

    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list) throws Exception {

        if(in.readableBytes()>BASE_LEN){

            if(in.readByte()== (byte)TAG){// 读取开始标识
                in.readBytes(6);//跳过地址长度
                int length =in.readByte();// 读取长度
                in.resetReaderIndex();//重置读指针，获取整体报文
                byte[] bw=null;
                try{
                     bw = in.readBytes(length+8+2).array();
                   System.out.println("获取报文为："+Arrays.toString(bw)+"获取报文时间："+System.currentTimeMillis());

                }catch (Exception e){
                   log.error("读取错误，{}",e.getMessage());
                }
                boolean flag =BwUtil.getScFromBW(bw);// 校验报文
                //104  校验成功！！1
                if(flag){
//                    报文攻击，优化记录日志方式，校验后的报文进行存储
                    log.info("get bw  is ：{}",Arrays.toString(bw));
                   BW msg = BwUtil.byte2Object(bw);// 或者报文对象

                   list.add(msg);//返回给后台
                }
            }
        }
    }
}
